package com.client.messages;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

public class MessageDispatcher2 {
private static Connection connection;
	
	@Resource(mappedName="jms/ConnectionFactory")
	 private static ConnectionFactory connectionFactory;
	
	@Resource(mappedName="jms/Topic")
	 private static Topic topic;
	 static Session mySess = null;
	 MessageProducer myMsgProducer;
	 ObjectMessage message;
	 MessageConsumer myMsgConsumer;
	 
	 public MessageDispatcher2(){
		 try{
				connectionFactory  = new com.sun.messaging.ConnectionFactory();
				connection = connectionFactory.createConnection();
				mySess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
				topic = new com.sun.messaging.Topic("moving");
				
				myMsgProducer = mySess.createProducer(topic);
				myMsgConsumer = mySess.createConsumer(topic);
				
				message = mySess.createObjectMessage();
			
		        connection.start();
				
				} catch (Exception jmse) {
		            System.out.println("Exception occurred : " + jmse.toString());
		            jmse.printStackTrace();
		        }finally{
		        	
		        }
	 }
	 
	public void createMessage(int x, int y, int t, Byte id){
		TemplateMessage msg = new TemplateMessage(x, y, t, id);
		try{
			 message.setObject(msg);
			 System.out.println("Sending message");
			 myMsgProducer.send(message);
			 
		 }catch (JMSException e) {
			 System.err.println("Consumer sender \n");
		}
	}
	 
		@Override
	protected void finalize() throws Throwable {
			try {
	    		if(connection != null)
	    				connection.close();
	    		if(mySess != null)
	    				mySess.close();
	    		System.err.println("close all");
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}

		public MessageConsumer getMyMessageConsumer() {

			try {
				myMsgConsumer = mySess.createConsumer(topic);
				
			} catch (JMSException e) {
				e.printStackTrace();
			}
			return myMsgConsumer;
		}
}
